package com.zx.framework.plat.login;

import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.code.kaptcha.Constants;
import com.zx.framework.core.env.CONST;
import com.zx.framework.core.env.IMenuPosition;
import com.zx.framework.core.exception.NoModifyPasswordException;
import com.zx.framework.core.util.BeanUtil;
import com.zx.framework.core.util.DatetimeUtils;
import com.zx.framework.core.util.SecurityUtil;
import com.zx.framework.core.util.StringUtil;
import com.zx.framework.plat.PlatController;
import com.zx.framework.plat.company.po.Company;
import com.zx.framework.plat.dept.po.Dept;
import com.zx.framework.plat.module.po.Module;
import com.zx.framework.plat.role.po.Role;
import com.zx.framework.plat.user.po.User;
import com.zx.framework.plat.user.vo.UserVo;
import com.zx.framework.web.exception.UIException;
@Component
public class LoginAdapterController extends PlatController {
	private static final Logger LOGGER = Logger
			.getLogger(LoginAdapterController.class);
	//密码加密规则 aes md5
	@Resource
	protected String passwordType = "md5";
	/**
	 * 检测登录用户
	 * @param loginId
	 * @param password
	 * @param kaptcha
	 */
	protected void checkUser(String loginId, String password, String kaptcha){
		try {
			if (StringUtil.isEmpty(loginId)) {
				throw new UIException(getMessage("e.login.id.empty"));
			}
			if (StringUtil.isEmpty(password)) {
				throw new UIException(getMessage("e.login.password.empty"));
			}

			if (StringUtil.isEmpty(kaptcha)) {
				throw new UIException(getMessage("e.kaptcha.no"));
			}

			String code = getSessionObject(Constants.KAPTCHA_SESSION_KEY,
					String.class);
			if (StringUtil.isEmpty(code)) {
				throw new UIException(getMessage("e.kaptcha.no"));
			}
			kaptcha = kaptcha.toLowerCase();
			code = code.toLowerCase();
			if (!kaptcha.equals(code)) {
				throw new UIException(getMessage("e.kaptcha.incorrect"));
			}
			
			User login  = userService.findUserByLoginId(loginId);
			
			if(login==null){
				throw new UIException(getMessage("e.notfound.user",loginId));
			}
			
			//如果未修改过密码
			if(1 != login.getPasswordModify()){
				throw new NoModifyPasswordException(getMessage("e.password.needModify"));
			}
			
			if(login.getPasswordStart()==null
					|| login.getPasswordEnd()==null){
				throw new UIException(getMessage("e.user.password.noeffect"));
			}
			Date now = new Date();
			if(login.getPasswordStart().after(now)){
				throw new UIException(getMessage("e.user.password.effectto", DatetimeUtils.dateToString(now, "yyyy-MM-dd HH:mm")));
			}
			if(login.getPasswordEnd().before(now)){
				throw new UIException(getMessage("e.user.expired", DatetimeUtils.dateToString(login.getPasswordEnd(), "yyyy-MM-dd HH:mm")));
			}
			String encryptPassword = "";
			switch (passwordType) {
				case "md5":
					encryptPassword = SecurityUtil.md5(login.getId()+password);
					break;
				case "aes":
					encryptPassword = SecurityUtil.encryptAES(login.getId()+password);
					break;
				default:
					//明文传输
					encryptPassword = password;
					break;
			}
			if(!encryptPassword.equals(login.getPassword())){
				throw new UIException(getMessage("e.login.password.error"));
			}
			UserVo user = new UserVo();
			BeanUtil.copyProperties(login, user);
			setUserVoSession(user);
		} catch (Exception e) {
			LOGGER.error("",e);
			throw new  UIException(e.getMessage());
		}
	}
	/**
	 * 设置session中的用户信息
	 * @param user
	 */
	protected void setUserVoSession(UserVo user){
		
		List<Company> companys = companyService.findUserCompany(user.getId());
		user.setCompanys(companys);
		
		List<Dept> depts =deptService.findUserDepts(user.getId());
		user.setDepts(depts);
		if(!depts.isEmpty()){
			user.setDept(depts.get(0));
		}
		
		List<Role> roles = roleService.findUserRoles(user.getId());
		user.setRoles(roles);
		
		List<Module> modules = moduleService.findUserModules(user.getId(), IMenuPosition.MENU_PLATFORM_WEB,-1);
		for (Module module : modules) {
			if(StringUtil.isNotEmpty(module.getUrl())){
				//外链地址不做权限验证
				if(module.getUrl().indexOf("http://")!=-1){
					user.getUrls().add(module.getUrl());
				}
				else{
					user.getUrls().add("/"+module.getUrl());
				}
			}
		}
		user.setPassword("******");
		setSessionObject(CONST.SESSION_KEY, user);
		setSessionObject(CONST.AUTHEN_SESSION_KEY, user.getUrls());
	}
	/**
	 * 单点登录，获取单点登录的url
	 * @param loginId 登录id
	 * @param pwd 登录密码
	 * @param key 登录的key
	 * @return
	 */
	protected String getSsoUrl(String loginId,String pwd){
		 String lid = SecurityUtil.encryptAES(loginId);
		 String lpwd = SecurityUtil.encryptAES(pwd);
		 String key = System.currentTimeMillis()+"|"+lid+"|"+lpwd+"|";
		 return "/sso/login/"+SecurityUtil.encryptAES(key);
	}
	/**
	 * 验证sso登录用户
	 * @param key
	 */
	protected void checkSso(String key){
		String keyReal = SecurityUtil.decryptAES(key);
		String[] complex = keyReal.split("\\|");
		String kaptcha = "zxkj";
		//设置一个session值，避免没有验证码
		setSessionObject(Constants.KAPTCHA_SESSION_KEY, kaptcha);
		checkUser(SecurityUtil.decryptAES(complex[1]), 
				SecurityUtil.decryptAES(complex[2]), kaptcha);
	}
}
